'''
@Coding: utf-8 
@Product: agro-traceability
@Author: rtf
@Time: 2020-08-14 14:12:52
@FileName: run.py
@Software: PyCharm Community Edition
'''


from cryptography.fernet import Fernet
from trump import app, config
from trump.query import get_item


@app.listener('after_server_start')
async def after_server_start(request, loop):
    pass


@app.middleware('request')
async def halt_request(request):
    if request.method in ["POST", "PUT"] and "upload" not in request.url:
        params = request.json
        del_params = list()
        if isinstance(params, dict):
            for key in params:
                if not params.get(key) and ("_date" in key or "_time" in key):
                    del_params.append(key)
            for x in del_params:
                del params[x]


@app.middleware('response')
async def handle_response(request, response):
    # if request.method in ["POST", "PUT"]:
    #     result, msg = await except_process(restapi.app, request, response)
    #     if not result:
    #         return fail(msg)
    pass


async def loaduser(app, request):
    user = await get_item(app.ctx.pool, "users_view", request.ctx.session.get("uid"), column="username")
    if user:
        role = user.get("role") if user.get("role") else None
        if role == "STUDENT":
            table_name = "student"
            column_name = "student_no"
        elif role == "TEACHER":
            table_name = "teacher"
            column_name = "teacher_no"
        else:
            table_name = "manager"
            column_name = "account"

        user = await get_item(app.ctx.pool, table_name, user.get("username"), column=column_name)
        if user:
            user["role"] = role
    request.ctx.user = user


class Crypto():
    def __init__(self):
        key = b'09aXvR2PiKwMKsusm4IiWKAumuMqeCe5OWWF-KnF8lY='
        self.f = Fernet(key)

    def encrypt(self, string):
        return self.f.encrypt(bytes(string, 'utf8')).decode('utf8')

    def decrypt(self, string):
        return self.f.decrypt(bytes(string, 'utf8')).decode('utf8')


@app.app.listener('before_server_start')
async def add_ws_clients(app, loop):
    app.ctx.clients = {}
    app.ctx.fernet = Crypto()


@app.app.signal("user.registration.created")
async def send_registration_email(**context):
    print("************888", context)

app.static('/export', 'export')
app.static('/download', 'upload')
if __name__ == '__main__':
    app.url_prefix = '/api/online'
    app.restapi.user_loader = loaduser
    app.run(auto_reload=True, port=config.PORT if hasattr(config, "PORT") else 9839)
